import { ItemStack, ItemTypes } from "@minecraft/server";
import { Game, GameComponent } from "@sapi-game/main";
import { Duration, RandomUtils } from "@sapi-game/utils";
import { PillarOfFortuneMainState } from "../states/mainState";

export class PillarOfFortuneRandomItem extends GameComponent<
    PillarOfFortuneMainState,
    { interval: number }
> {
    private ids?: string[];
    override onAttach(): void {
        if (!this.options) return;
        this.runner.run(async (r) => {
            await this.loadData();
        });
        this.subscribe(
            Game.events.interval,
            () => {
                this.giveRandomItemToAll();
            },
            Duration.fromSeconds(this.options.interval)
        );
    }

    /**加载ids */
    async loadData() {
        this.ids = (await import("../idMap")).ids;
    }

    /**给所有玩家随机物品 */
    giveRandomItemToAll() {
        if (!this.ids) return;
        this.context.players.forEach((p) => {
            if (!p.alive) return;
            const item = RandomUtils.choice(this.ids!);
            if (!item) return;
            const itemType = ItemTypes.get(item);
            if (!itemType) {
                p.sendMessage("§c无法找到物品:" + item + ",请反馈给管理员");
                return;
            }
            p.giveItem(new ItemStack(itemType));
        });
    }
}
